using System;

namespace ButsaForecast
{
    internal static class Utils
    {
        public static double GetDistance(double[] v1, double[] v2)
        {
            if (v1.Length != v2.Length)
                throw new ArgumentException();

            double distance = 0;
            for (int i = 0; i < v1.Length; i++)
            {
                distance += (v1[i] - v2[i])*(v1[i] - v2[i]);
            }
            distance = Math.Sqrt(distance);
            return distance;
        }

        public static double GetAverage(double[] data)
        {
            int len = data.Length;
            if (len == 0)
                throw new Exception("No data");

            double sum = 0;
            for (int i = 0; i < data.Length; i++)
                sum += data[i];
            return sum/len;
        }

        public static double GetVariance(double[] data)
        {
            int len = data.Length;
            // Get average

            double avg = GetAverage(data);

            double sum = 0;
            for (int i = 0; i < data.Length; i++)
                sum += Math.Pow((data[i] - avg), 2);
            return sum/len;
        }

        public static double GetStdev(double[] data)
        {
            return Math.Sqrt(GetVariance(data));
        }

        public static void GetCorrelation(double[] x, double[] y, ref double covXY, ref double pearson)
        {
            if (x.Length != y.Length)
                throw new Exception("Length of sources is different");
            double avgX = GetAverage(x);
            double stdevX = GetStdev(x);
            double avgY = GetAverage(y);
            double stdevY = GetStdev(y);
            int len = x.Length;

            for (int i = 0; i < len; i++)
                covXY += (x[i] - avgX)*(y[i] - avgY);
            covXY /= len;
            pearson = covXY/(stdevX*stdevY);
        }
    }
}